//
//  KKStatusViewModel.swift
//  SinaWeiBo
//
//  Created by King.Kong. on 16/5/27.
//  Copyright © 2016年 King.Kong. All rights reserved.
//

import UIKit

class KKStatusViewModel: NSObject {
    
    //静态的正则表达式对象
    static let emoticonRegex = try! NSRegularExpression(pattern: "\\[.*?\\]", options: [])
    //话题的正则表达式对象
    static let topicRegex = try! NSRegularExpression(pattern: "#.*?#", options: [])
    //@某个人的正则表达式对象 @霍建华: @赵薇
    static let atSomeOneRegex = try! NSRegularExpression(pattern: "@\\w+", options: [])
    //url的正则表达式对象
    static let urlRegex = try! NSRegularExpression(pattern: "(http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?", options: [])

    //1. init方法中设置无法调用didSet
    //2. 在didSet内部设置 也无法调用didSet
    var status: KKStatus?
    //    {
    //
    //        didSet {
    //            status = xxx
    //        }
    //    }
    
    //认证类型的图片
    var veritiedImage: UIImage?
    var mbrankImage: UIImage?
    var headImageURL: NSURL?
    //微博来源
    var sourceText: String?
    //每次执行
    var time: String? {
        return NSDate.sinaDate(status?.created_at ?? "")?.fullDescription()
    }
    
    var repostsText: String?
    
    var commentsText: String?
    
    var attitudesText: String?
    //原创微博的属性字符串
    var originalAttrbuiteString: NSAttributedString?
    //转发微博的正文
    var reweetedAttrbuiteString: NSAttributedString?
    //视图初始化
    init(status: KKStatus) {
        super.init()
        self.status = status
        //处理用户头像的地址
        headImageURL = NSURL(string: status.user?.profile_image_url ?? "")
        //处理认证类型的图片
        dealVeitiedImage()
        //处理用户等级的图片
        dealMbrankImage()
        //处理微博时间
        //不会实时修改
//        time = NSDate.sinaDate(status.created_at ?? "")?.fullDescription()
        //微博来源
        dealSoureText()
        
        commentsText = dealToolBarText(status.comments_count, defaultText: "评论")
        repostsText = dealToolBarText(status.reposts_count, defaultText: "转发")
        attitudesText = dealToolBarText(status.attitudes_count, defaultText: "赞")
        
        originalAttrbuiteString = dealWeiboText(status.text ?? "")
        reweetedAttrbuiteString = dealWeiboText(status.retweeted_status?.text ?? "")

        
    }
}

extension KKStatusViewModel {
    
    //在这个方法计算底部工具条显示的文字
    //如果没有评论或者转发或者赞  就显示默认文字
    //- 有相关的数据 就显示对应的数据,但是如果超过一万条 就应该显示多少万条
    func dealToolBarText(count: Int,defaultText: String) -> String {
        
        //let count = 11000
        if count <= 0 {
            return defaultText
        }
        //大于一万
        if count >= 10000 {
            return "\(Double(count / 1000) / 10)万"
        }
        return "\(count)"
    }

    private func dealSoureText() {
        //<a href=\"http://app.weibo.com/t/feed/1tqBja\" rel=\"nofollow\">360安全浏览器</a>
        let startFlag = "\">"
        let endFlag = "</a>"
        let str = status?.source ?? ""
        let startRange = str.rangeOfString(startFlag)
        let endRange = str.rangeOfString(endFlag)
        if let start = startRange, end = endRange {
            let range = start.endIndex..<end.startIndex
            sourceText = str.substringWithRange(range)
        }
        //不满足截取条件 就不赋值
    }

    private func dealMbrankImage() {
        let mbType = status?.user?.mbrank ?? 0
        if mbType > 0 && mbType < 7 {
            // 1 ~ 6
            //转译会自动加上 optional
            mbrankImage = UIImage(named: "common_icon_membership_level\(mbType)")
        }
    }
    
    private func dealVeitiedImage() {
        let veriteidType = status?.user?.verified ?? 0
        if veriteidType == 1 {
            veritiedImage = UIImage(named: "avatar_vip")
        }
    }
    
    //处理微博文本 转换成属性文本
    func dealWeiboText(sourceText: String) -> NSAttributedString {

        //使用正则表达式 来查找 表情字符串
        //[奥特曼]说[爱你],[拜拜]
        let results = KKStatusViewModel.emoticonRegex.matchesInString(sourceText, options: [], range: NSRange(location: 0, length: sourceText.characters.count))
        let strM = NSMutableAttributedString(string: sourceText)
        
        //遍历结果集合 获取单个表情字符串
        for result in results.reverse() {
            //通过表情字符串在分组数组中查找 表情字符串对应的 '表情模型"'
            let range = result.rangeAtIndex(0)
            let emoticonStr = (sourceText as NSString).substringWithRange(range)
            if let em = findEmoticonWithChs(emoticonStr) {
                let image = UIImage(contentsOfFile: em.imagePath ?? "")
                //获取字体对应的行高
                let font = UIFont.systemFontOfSize(originalContentLabelFontSize)
                let fontWidth = font.lineHeight
                let imageText =  NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: .ScaleToFill, attachmentSize: CGSize(width:fontWidth ,height:fontWidth), alignToFont: font, alignment: .Center)

                //获取表情模型中的 表情图片路径
                //通过表情图片的路径 实例化附件对象
                //通过附件对象 实例化 属性字符串
                //完成属性字符串的替换
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
                //原创微博的属性字符串 就已经完成了赋值
            }
        }
        //在给特殊的文本添加高亮颜色前先设置基本颜色
        strM.addAttributes([NSForegroundColorAttributeName : UIColor.darkGrayColor()], range: NSRange(location: 0, length: strM.length))
        //设置文字的大小
        strM.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(originalContentLabelFontSize)], range:  NSRange(location: 0, length: strM.length))
        //查找字符串中的话题的字符串,添加颜色
        //addTopicHighlited(strM)
        addHighlighted(strM, regex: KKStatusViewModel.topicRegex)
        //给@某人添加高亮
        addHighlighted(strM, regex: KKStatusViewModel.atSomeOneRegex)
        //url的高亮显示
        addHighlighted(strM, regex: KKStatusViewModel.urlRegex)

        return strM
    }
    
    private func addHighlighted(str: NSMutableAttributedString,regex: NSRegularExpression) {
        //获取属性字符串的对应的字符串
        let topicStr = str.string
        let results =  regex.matchesInString(topicStr, options: [], range: NSRange(location: 0, length: topicStr.characters.count))
        //遍历结果
        for result in results {
            //取出话题子串
            let range = result.rangeAtIndex(0)
            //取出话题子串
            let border = YYTextBorder(fillColor: UIColor.darkGrayColor(), cornerRadius: 3)
            
            //实例化高亮对象
            let highlithed = YYTextHighlight()
            highlithed.setColor(UIColor.redColor())
            highlithed.setBackgroundBorder(border)
            //把"高亮"属性设置到某个文本范围
            str.yy_setTextHighlight(highlithed, range: range)
            //let subStr = (topicStr as NSString).substringWithRange(range)
            //给特殊的字符串添加高亮
            str.addAttributes([NSForegroundColorAttributeName : UIColor.blueColor()], range: range)
            //print(subStr)
        }
    }
    
    //根据表情字符串查找对应的模型对象
    private func findEmoticonWithChs(chs: String) -> KKEmoticon? {
        
        
        //获取分组的表情
        for p in KKEmoticonManager.sharedEmoticonTools.packages {
            //获取二维数组中的每一个小数组
            for emoticons in p.sectionEmoticon {
                //在数组中根据表情字符串查找对应的模型对象
                let array = emoticons.filter({ (em) -> Bool in
                    //返回查找的条件  就是目标对象
                    return chs == em.chs
                })
                print(array)
                if array.count > 0 {
                    //根据chs 查询到了模型对象
                    return array.first
                }
            }
        }
        
        return nil
    }

}

